/*
 * 
 * @UI_AddClassHover class plugin
 */
$.fn.UI_AddClassHover = function (_class) {
    var $this = $(this);
    $this.bind("touchstart", function () {
        var $this = $(this);
        $this.addClass(_class)
                .bind("touchend", function () {
                    $this.removeClass(_class);
                });
    });
};


UI_Page.prototype.uiHeader = function (options) {
    var LAYOUT = options.page == undefined ? this.LAYOUT : "#" + options.page;
    (function () {
        var params = {
            text: "Header text",
            image: ""
        };



        $.extend(params, options);

        var html = '<div class="UI_Header"><div class="Inner">\n\
                    <a class="Header_btn navInfo Right_1"><span class="fa fa-user"></span></a>\n\
                    <span class="Header_text"><div class="image" style="background:url(' + params.image + ') no-repeat"></div><div class="around-marquee"><label>' + params.text + '</label></div></span></div></div>';

        $(LAYOUT + " .UI_Body").before(html);
        $(LAYOUT + " .UI_Header .Header_btn").UI_AddClassHover("hover");

        setTimeout(function () {
            if ($('.around-marquee').width() < $('.around-marquee label').width()) {
                $('.around-marquee label').addClass('marquee');
            }
        }, 500);

        //Menubar
        Infobar.initEvent();
    })();
};


UI_Page.prototype.uiWaitOptions = {
    lines: 12, // The number of lines to draw
    length: 5, // The length of each line
    width: 2, // The line thickness
    radius: 7, // The radius of the inner circle
    corners: 1, // Corner roundness (0..1)
    rotate: 0, // The rotation offset
    direction: 1, // 1: clockwise, -1: counterclockwise
    color: '#fff', // #rgb or #rrggbb or array of colors
    speed: 1, // Rounds per second
    trail: 60, // Afterglow percentage
    shadow: false, // Whether to render a shadow
    hwaccel: false, // Whether to use hardware acceleration
    className: 'spinner', // The CSS class to assign to the spinner
    zIndex: 9999 // The z-index (defaults to 2000000000)
};
/*
 * 
 * @Infobar class
 */
//var Html_wait = '<div class="Waiting"><div class="fa fa-spinner"></div></div>';
var Html_wait = '<div class="Wait"><div class="Wait_inner"></div></div>';


var Infobar = new function () {
    var allowClick = 0;
    this.initEvent = function () {
        $(".navInfo").off("tap");
        $(".navInfo").on("tap", function () {
            allowClick++;
            if (allowClick === 1) {
                if (!Infobar.is_show()) {
                    Infobar.show();
                } else {
                    Infobar.hide();
                }
            }

        });
    };

    this.is_show = function () {
        return $(".layout_disabled").length > 0 ? true : false;
    };

    this.show = function () {
        $("#UI_InfoBar").css("opacity", 1);
        $("#UI_Page").addClass("push_right");
        $(".Header_btn.navInfo").addClass("active");
        $(".UI_Body,.UI_ContentBody").addClass("layout_disabled");

        //Init
        if ($("#UI_InfoBar script").length == 0) {
            this.init();
        }

        setTimeout(function () {
            allowClick = 0;
            $(".layout_disabled").on("tap", function () {
                Infobar.hide();
                //Infobar.destroy();
                $(".layout_disabled").off("tap");
            });
        }, 900);
    };

    this.hide = function () {
        $("#UI_Page").removeClass("push_right");
        $(".Header_btn.navInfo").removeClass("active");
        $(".layout_disabled").removeClass("layout_disabled");
        setTimeout(function () {
            allowClick = 0;
            $("#UI_InfoBar").css("opacity", 0);
        }, 500);
        //Infobar.destroy();
    };
    var check = 0;
    this.load = function (url) {
        check++;
        if (check === 1) {
            check = 0;
            $("#UI_InfoBar .Inner").load("app/" + url + ".html");
        }


    };

    this.wait = function () {
        $("#UI_InfoBar .Inner").html(Html_wait);
        new Spinner(_this.uiWaitOptions).spin(document.querySelector('.Wait_inner'));
    };

    this.init = function () {
        $("#UI_InfoBar").css("opacity", "1");
        setTimeout(function () {
            $.get("app/user/index.html", function (data) {
                $("#UI_InfoBar .Wait").after(data);
                setTimeout(function () {
                    $(".UI_BarBody").addClass("UI_BarBody_Active");
                    $("#UI_InfoBar .Wait").addClass("slideup");
                }, 200);
            });
        }, 400);
    };

    this.destroy = function () {
        setTimeout(function () {
            Infobar.wait();
        }, 500);
    };
};

var Popup = function () {
    this.open = function (href, effect, done) {

        if (!this.isOpen()) {
            effect = effect == undefined ? "" : effect;
            $(".UI_Popup").addClass("UI_Popup_open " + effect);
            setTimeout(function () {
                // $(".UI_PopupBody .Content").load("app/" + href + ".html");
                if (typeof done == 'function') {
                    done();
                }
            }, 400);
        }
    };

    this.isOpen = function () {
        return $(".UI_Popup_open").length > 0 ? true : false;
    };

    this.close = function (done) {
        $(".UI_Popup_open").addClass("ZoomOut");
        setTimeout(function () {
            $(".UI_Popup").attr("class", "UI_Popup");
            if (typeof done == 'function') {
                done();
            }
//            $(".UI_PopupBody .Content").empty();
//            $('.UI_PopupBody .Wait').show();
        }, 400);
    };

    this.hideWaiting = function () {
        $('.UI_PopupBody .Wait').hide();
    };

};

var PopupPanel = {
    flag: false,
    isOpen: function () {
        return $(".UI_PopupPanel").is(":visible");
    },
    close: function () {
        $(".UI_PopupPanel .Scroll_Inner .ListView").empty();
        $(".UI_PopupPanel").fadeOut();
        $(".Header_text").removeClass("active");
        //console.log("closed");
        PopupPanel.flag = false;

    }, open: function () {
        $(".UI_PopupPanel").css("display", "block");
        setTimeout(function () {
            PopupPanel.flag = true;
        }, 500);
    }
};

var TextPanel = {
    init: function () {
        $(".Panel_Cancel").on("tap", function () {
            $(".UI_TextPanel textarea").val("");
            TextPanel.close();
        });

        $(".UI_TextPanel button").UI_AddClassHover("hover");

    },
    isOpen: function () {
        return $(".UI_TextPanel").is(":visible");
    },
    close: function () {
        $(".UI_TextPanel").hide();
    },
    show: function (done) {
        $(".UI_TextPanel").show();
        if (typeof done == 'function') {
            done();
        }
    }
}

/*
 *@Toast Class
 */

var Toast = new function () {
    /*
     * @size {large,small(default)}
     * @width {number}
     * @height {number}
     * @position {top, bottom, center(default)}
     * @type {success, failure, warning}
     * @text {string}
     * @timeout {number | default 2000, custom}
     * @id {string}
     */
    this.IsDialog = false;

    this.show = function (options) {
        Toast.close();
        var type = "";
        switch (options.type) {
            case "success":
                type = '<span class="fa fa-check"></span>';
                break;
            case "failure":
                type = '<span class="fa fa-frown-o"></span>';
                break;
            case "warning":
                type = '<span class="fa fa-exclamation-circle"></span>';
                break;
            default:
                break;
        }

        var position = "";
        switch (options.position) {
            case "top":
                position = 'Toast_message_top ';
                break;
            case "bottom":
                position = 'Toast_message_bottom ';
                break;
            default:
                position = 'Toast_message_center ';
                break;
        }

        var height = options.height == undefined ? "" : "height:" + options.height + "px;";
        var width = options.width == undefined ? "" : "width:" + options.width + "px;";
        var size = options.size == "large" ? "Toast_message_large " : "";
        var id = options.id == undefined ? "" : "id = '" + options.id + "'";
        if ($(".Toast_message").length == 0 || $(".Toast_button_load").length > 0) {
            Toast.close();
            $("body").append('<div ' + id + ' style="' + height + width + '" class="Toast_message ' + size + position + '"><div class="Toast_message_inner">' + type + options.text + '</div></div>');
        }

        var timeout = options.timeout == undefined ? 2000 : options.timeout;

        if (timeout != "custom") {
            setTimeout(function () {
                var id = options.id == undefined ? "" : options.id;
                $("#" + id).remove();
            }, timeout);
        }
    };

    this.button = function (options) {
        this.show(options);
        $(".Toast_message_inner").UI_AddClassHover("hover");
        $(".Toast_message_inner").off("tap").addClass("Toast_button");
        $(".Toast_message_inner").on("tap", function () {
            if (typeof options.click == 'function') {
                options.click();
                if (options.tap == "close") {

                }
            }
            Toast.close();
        });
    };

    this.buttonLoad = function (text) {
        $(".Toast_button").addClass("Toast_button_load").html('<span class="toast_preload"></span> ' + text).removeClass("Toast_button");
    };

    this.close = function (id) {
        $(".Toast_message").remove();
    };

    this.notification = function (options) {
        var notifi = _this.storage.get("notification");
        if (notifi == "" || parseInt(notifi) == 0) {
            var params = {
                text: "",
                top: "",
                left: "",
                right: "",
                bottom: ""
            };
            $.extend(params, options);
            var html = ' <div class="UI_Notification"><div class="Wrapper"><div class="Layout"></div><div class="Notification" style="top:' + params.top + 'px;left:' + params.left + 'px;right:' + params.right + 'px;bottom:' + params.bottom + 'px">\n\
            <div class="Inner">' + params.text + '</div></div></div></div>';
            $("body").append(html);

            $(".UI_Notification .Layout").on("tap", function () {
                Toast.notification_close();
            });

            $(".UI_Notification .Inner").on("tap", function () {
                PopupPanel.open();
                Toast.notification_close();
                Toast.close();
                List.gets(function () {
                    $("#Wait_PopupPanel").fadeOut();
                });
            });
        }
    };

    this.notification_close = function () {
        $(".UI_Notification").remove();
        _this.storage.set("notification", 1);
    };

    /*
     * @width {number}
     * @height {number}
     * @mode {icon(default), icon-text}
     * @type {success, loading(default), failure, warning}
     * @text {string}
     */
    this.progress = function (options) {

        var mode = "";
        var text = "";
        if (options.text != undefined) {
            mode = 'Toast_proccess_text';
            text = options.text;
        }
        var turnoff = options.turnoff == undefined ? false : options.turnoff;
        var type = "";
        switch (options.type) {
            case "success":
                type = '<span class="fa fa-check"></span>' + text;
                break;
            case "failure":
                type = '<span class="fa fa-frown-o"></span>' + text;
                break;
            case "warning":
                type = '<span class="fa fa-exclamation-circle"></span>' + text;
                break;
            default:
                type = '<span class="toast_preload"></span>' + text;
                break;
        }

        var height = options.height == undefined ? "" : "height:" + options.height + "px;";
        var width = options.width == undefined ? "" : "width:" + options.width + "px;";
        var class_effect = options.effect == undefined ? "" : options.effect;
        var html = '<div class="Toast_proccess_wrapper">\n\
                        <div style="' + width + height + '" class="Toast_proccess ' + mode + ' ' + class_effect + '">' + type + '</div></div>';
        $("body").append(html);

        $(".Toast_proccess").on("tap", function () {
            $(".Toast_proccess_wrapper").remove();
            $(".Toast_proccess").off("tap");
        });

        if (turnoff != false) {
            setTimeout(function () {
                if (options.effect != undefined) {
                    $(".Toast_proccess").removeClass("rollIn").addClass("rollOut");
                    setTimeout(function () {
                        $(".Toast_proccess_wrapper").remove();
                    }, 400);
                } else {
                    $(".Toast_proccess_wrapper").remove();
                }

            }, turnoff);
        }

    };

    /*
     * @type {success(default), failure, warning}
     * @text {string}
     * @turnoff {number | default 1200}
     */
    this.progressNext = function (options) {

        if (options == undefined) {
            $(".Toast_proccess_wrapper").remove();
            //$("body").removeClass("toasting");
        } else {
            var height = options.height == undefined ? "" : "height:" + options.height + "px;";
            var width = options.width == undefined ? "" : "width:" + options.width + "px;";
            var turnoff = options.turnoff == undefined ? false : options.turnoff;
            var type = "";
            var text = options.text == undefined ? "" : options.text;
            switch (options.type) {
                case "preload":
                    type = '<span class="toast_preload"></span>' + text;
                    break;
                case "success":
                    type = '<span class="fa fa-check"></span>' + text;
                    break;
                case "failure":
                    type = '<span class="fa fa-frown-o"></span>' + text;
                    break;
                case "warning":
                    type = '<span class="fa fa-exclamation-circle"></span>' + text;
                    break;
                default:
                    type = '<span class="fa fa-check"></span>' + text;
                    break;
            }

            $(".Toast_proccess").html(type).attr("style", width + height);
            $(".Toast_proccess").on("tap", function () {
                $(".Toast_proccess_wrapper").remove();
                $(".Toast_proccess").off("tap");
            });
            if (turnoff != false) {
                setTimeout(function () {
                    $(".Toast_proccess_wrapper").remove();
                }, turnoff);
            }
        }
    };

    this.progressNextToToast = function (options) {
        $(".Toast_proccess_wrapper").remove();
        this.show(options);
    };
};

var Dialog = {
    IsShow: false,
    effectIn: "",
    effectOut: "",
    showConfirm: function (options) {
        if (!this.IsShow) {
            this.IsShow = true;
            var params = {
                title: "Dialog header",
                content: "Dialog content",
                buttons: [{
                        id: "Confirm_ok",
                        text: "Ok",
                        type: "bold"
                    }],
                effectIn: "ZoomIn_3",
                effectOut: "ZoomOut_4",
                event: ""
            };
            $.extend(params, options);
            this.effectIn = params.effectIn;
            this.effectOut = params.effectOut;

            var buttons = '';
            var length = 0;
            $.each(params.buttons, function (i, item) {
                length++;
                var type = (item.type !== undefined ? item.type : '');
                buttons += "<button class='" + type + "' id='" + item.id + "'>" + item.text + "</button>";
            });
            var html = '<div class="UI_Dialog UI_Dialog_' + _this.appOs + ' modal"><div class="UI_Dialog_layout"></div>\n\
    <div class="UI_Dialog_content"><div class="modal-dialog ' + params.effectIn + '">\n\
        <div class="modal-content">\n\
            <div class="modal-header">\n\
                <h4 class="modal-title">' + params.title + '</h4>\n\
            </div>\n\
            <div class="modal-body">' + params.content + '</div>\n\
            <div class="modal-footer Button_' + length + '">' + buttons + '</div>\n\
        </div></div><!-- /.modal-content -->\n\
    </div><!-- /.modal-dialog -->\n\
</div><!-- /.modal -->';
            $("body").append(html);
            if (typeof params.event == 'function')
                params.event();

            setTimeout(function () {
                $(".UI_Dialog").removeClass(params.effectIn);
            }, 300);

//            $(".UI_Dialog_layout").on("tap", function () {
//                Dialog.close();
//            });

            $(".UI_Dialog button").UI_AddClassHover("hover");
        }
    },
    showAdv: function (tvshows) {
        if (!this.IsShow) {
            this.IsShow = true;
            var pW = $(window).width() * 90 / 100;
            var pH = pW * 460 / 820 + 5;
            var mobile = false;
            if ($(window).width() <= 514) {
                pW = $(window).width() * 90 / 100;
                pH = pW;
                mobile = true;
            }

            var li = '';
            for (var i = 0; i < tvshows.length; i++) {
                var item = tvshows[i];
                var join = item.starting == 1 ? '<button data-id_channel="' + item.channel_id + '" data-id_tvshow="' + item.id + '" data-name="' + item.name + '" data-background_show="' + item.background + '" data-logo_channel="' + item.logo + '" data-time="' + item.schedule + '" data-type_qa="' + item.type + '" data-sound_welcome="' + item.sound_welcome + '" data-sound_bg="' + item.sound_bg + '" class="join"><span></span>Tương tác ngay</button>' : '';
                if (mobile == true && item.wap_poster != "") {
                    li += '<div class="swiper-slide" style="width:' + (pW - 10) + 'px;height:' + (pH - 10) + 'px"><img src="' + _this.Base_Upload + item.wap_poster + '"/>' + join + '</div>';
                }else if(mobile==false && item.web_poster!=""){
                    li += '<div class="swiper-slide" style="width:' + (pW - 10) + 'px;height:' + (pH - 10) + 'px"><img src="' + _this.Base_Upload +  item.web_poster + '"/>' + join + '</div>';
                }
            }
            var html = '<div class="UI_Dialog modal"><div class="UI_Dialog_layout"></div>\n\
            <div class="UI_Poster fadeInDown animated" style="width:' + pW + 'px;height:' + pH + 'px"><div class="Poster_inner">\n\
                <div class="swiper-container advSlider">\n\
		<div class="swiper-wrapper">' + li + '</div></div><a class="Close"></a>\n\
            </div></div>';
            $("body").append(html);

            $(".UI_Poster .Close").UI_AddClassHover("hover");
            $(".UI_Poster .Close").on("tap", function () {
                Dialog.close();
            });
            $('.advSlider').each(function () {
                $(this).swiper({
                    slidesPerView: 'auto'
                })
            });
            $(".UI_Poster .join").UI_AddClassHover("hover");
            $(".UI_Poster .join").off("tap");
            $(".UI_Poster .join").on("tap", function () {
                var $this = $(this);
                socket.io.disconnect();
                Dialog.close();
                Toast.progress({text: "Chuyển hướng chương trình...", width: 160, height: 101});
                var _data = {
                    id_channel: $this.data("id_channel"),
                    id_tvshow: $this.data("id_tvshow"),
                    name: $this.data("name"),
                    background_show: $this.data("background_show"),
                    logo_channel: $this.data("logo_channel"),
                    time: $this.data("time"),
                    type_qa: $this.data("type_qa"),
                    sound_welcome: $this.data("sound_welcome"),
                    sound_bg: $this.data("sound_bg")
                };
                Template.save(_data);
                Template.init(_data);

                $.get('app/index/index.html', function (html) {
                    $("#page_indexindex").html(html);
                    Template.active("page_indexindex", "offline", function () {
                        $("#page_indexstatistic").empty();
                        _this.redirect("index/index");
                    }, function () {
                        Toast.progressNextToToast({text: "Lỗi chuyển hướng chương trình.", id: "gv"});
                    });
                });

            });
        }
    },
    close: function (success) {
        this.IsShow = false;
        $(".modal-dialog").addClass(this.effectOut);
        $(".UI_Dialog_layout").css("opacity", "0");
        setTimeout(function () {
            $(".UI_Dialog").remove();
            if (typeof success == 'function') {
                success();
            }
        }, 300);

    }
};
